package com.googlecode.bip.dao.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.googlecode.bip.dao.UserReferentDAO;
import com.googlecode.bip.entity.IUserReferent;
import com.googlecode.bip.entity.impl.UserReferent;

/**
 *
 * @author Claude
 */
public class MySQLUserReferentDAO
    extends MySQLDAOBuilder<IUserReferent>
        implements UserReferentDAO
{
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger( MySQLUserReferentDAO.class );

    @Override //Listable<IQuestion>
    public IUserReferent newInstance( final ResultSet rSet )
        throws SQLException
    {
        return new UserReferent().set( rSet );
    }

    @Override
    public IUserReferent findUserReferent( final int iduser, final int idreferent )
        throws NamingException, SQLException
    {
        final String sql = "SELECT * FROM `userreferents` WHERE `iduser`=" + iduser + " AND `idreferent`=" + idreferent + ";";

        return getElement( sql );
    }

    @Override
    public List<IUserReferent> findUserReferents( final int iduser )
        throws NamingException, SQLException
    {
        final String sql = "SELECT * FROM `userreferents` WHERE `iduser`=" + iduser + ";";

        return getList( sql );
    }

    @Override
    public IUserReferent insertUserReferent( final int iduser, final int idreferent )
        throws NamingException, SQLException
    {
        final String sql = "CALL `add_user_referent`("
                            + iduser
                            + ", "
                            + idreferent
                            + ");";

        return executeQuery( sql );
    }

    @Override
    public boolean deleteUserReferent( final int iduser, final int idreferent )
        throws NamingException, SQLException
    {
        final String sql = "DELETE FROM `userreferents` WHERE `iduser`=" + iduser + " AND `idreferent`=" + idreferent + ";";

        int r = doUpdate( sql );

        if( logger.isDebugEnabled() ) {
            logger.debug( "deleteUserReferent r = " + r );
            }

        return true;
    }

    @Override
    public boolean deleteUserReferent(
        IUserReferent userReferent
        ) throws NamingException, SQLException
    {
        return deleteUserReferent(
                    userReferent.getIdUser(),
                    userReferent.getIdReferent()
                    );
    }

}
